<template>
  <el-upload class="upload-demo" action :before-upload="beforeUpload" :http-request="fnUploadRequest" :show-file-list="true" :on-remove="onRemove" :on-preview="onPreview" :file-list="fileList">
    <el-button size="small" type="primary">文件上传</el-button>
  </el-upload>
</template>

<script>
import { downloadFile } from '@/api/api'
import { editFiles } from '@/unils/utils'
export default {
  props: {
    showFiles: {
      type: Array,
      default: () => []
    },
  },
  data () {
    return {
      fileList: [],
      fileList2: []
    }
  },
  watch: {
    showFiles(newV, oldV) {
      // 用于显示
      this.fileList = editFiles(newV)[0]
      // 用于原文件提交
      this.fileList2 = editFiles(newV)[1]
    },
  },
  methods: {
    beforeUpload (file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isLt2M = file.size / 1024 / 1024 < 500 //这里做文件大小限制

      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 500MB!',
          type: 'warning',
        })
      }
      return isLt2M
    },
    fnUploadRequest(file) {
      this.fileList.push(file.file)
      this.$emit('getfiles', [this.fileList, this.fileList2])
    },
    onRemove(file, fileList) {
      // 删除后的上传文件处理
      this.fileList = fileList

      // 删除后的原文件处理
      this.fileList2 = []
      fileList.forEach(item => {
        if (item.id) {
          this.fileList2.push(item)
        }
      })
      this.$emit('getfiles', [this.fileList, this.fileList2])
    },
    // 组件中的文件点击下载
    onPreview (file) {
      if (file.id) {
        downloadFile({ id: file.id }).then(res => {
          if (res.code == 200) {
            window.open(res.data.url, '_self')
          }
        }).catch(e => {
          console.log(e)
        })
      }
    },
  },
}
</script>
<style lang="less" scoped>
</style>